﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using WordService.DBUtil;
using System.Xml;
using System.Data.SqlClient;
using WordService.Business.IBLL;
using WordService.Business;
using WordService.Model;

namespace WordLib.ConfigUI
{
    public partial class ConfigPanel : UserControl
    {
        public ConfigPanel()
        {
            InitializeComponent();
            LoadFormData();
        }

        private void LoadFormData()
        {
            SetFormValue("");
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (currentConStr == null || currentConStr.Equals(String.Empty))
            {
                LoadFormData();
            }
            else
            {
                SetFormValue(currentConStr);
            }
        }

        private String currentConStr;

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            if (this.txtInstance.Text.Trim().Equals(String.Empty))
            {
                builder.Append(DBUtility.DataSource + "=" + this.txtServerHost.Text + ";");
            }
            else
            {
                builder.Append(DBUtility.DataSource + "=" + this.txtServerHost.Text + @"\" + this.txtInstance.Text + ";");
            }
            builder.Append(DBUtility.Database + "=" + this.txtDatabase.Text + ";");
            if (this.cbbAuthMethod.SelectedIndex == 0)
            {
                builder.Append(DBUtility.IntegratedSecurity + "=True;");
            }
            else
            {
                builder.Append(DBUtility.IntegratedSecurity + "=False;");
                builder.Append(DBUtility.UserID + "=" + this.txtUserName.Text + ";");
                builder.Append(DBUtility.Password + "=" + this.txtPassword.Text + ";");
            }
            builder.Append(DBUtility.Pooling + "=" + this.chkIsPool.Checked + ";");
            UpdateConfig(builder.ToString());
            currentConStr = builder.ToString();
            SetFormValue(builder.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="conStr"></param>
        private void SetFormValue(String conStr)
        {
            if (conStr.Equals(String.Empty))
            {
                conStr = ConfigurationManager.ConnectionStrings[DBUtility.ConKey].ConnectionString;
                // 设置该程序需要使用的连接字符串
                this.currentConStr = conStr;
            }
            String[] keyValues = conStr.Split(';');
            foreach (String keyValue in keyValues)
            {
                if (keyValue.Equals(String.Empty))
                {
                    continue;
                }
                String key = keyValue.Split('=')[0];
                String value = keyValue.Split('=')[1];
                // 数据库服务器信息
                if (key.Equals(DBUtility.DataSource))
                {
                    if (value.Contains(@"\"))
                    {
                        String[] values = value.Split('\\');
                        if (!values[0].Trim().Equals(String.Empty))
                        {
                            this.txtServerHost.Text = values[0];
                        }
                        if (!values[1].Trim().Equals(String.Empty))
                        {
                            this.txtInstance.Text = values[1];
                        }
                    }
                    else
                    {
                        this.txtServerHost.Text = value;
                        this.txtInstance.Text = String.Empty;
                    }
                    continue;
                }
                // 用户名
                if (key.Equals(DBUtility.UserID))
                {
                    this.txtUserName.Text = value;
                }
                // 密码
                if (key.Equals(DBUtility.Password))
                {
                    this.txtPassword.Text = value;
                }
                // 数据库名称
                if (key.Equals(DBUtility.Database))
                {
                    this.txtDatabase.Text = value;
                }
                // 登陆方式
                if (key.Equals(DBUtility.IntegratedSecurity))
                {
                    if (Boolean.Parse(value))
                    {
                        this.txtUserName.Enabled = false;
                        this.txtPassword.Enabled = false;
                        this.cbbAuthMethod.SelectedIndex = 0;
                    }
                    else
                    {
                        this.cbbAuthMethod.SelectedIndex = 1;
                        this.txtUserName.Enabled = true;
                        this.txtPassword.Enabled = true;
                    }
                }
                // 连接池属性
                if (key.Equals(DBUtility.Pooling))
                {
                    if (Boolean.Parse(value))
                    {
                        this.chkIsPool.Checked = true;
                    }
                    else
                    {
                        this.chkIsPool.Checked = false;
                    }
                }
            }
            this.lblConStr.Text = conStr;
        }

        private void UpdateConfig(String newConString)
        {
            // 重载应用程序
            ConnectionStringSettings settings = new ConnectionStringSettings(DBUtility.ConKey,newConString,"System.Data.SqlClient");
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove(DBUtility.ConKey);
            config.ConnectionStrings.ConnectionStrings.Add(settings);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("ConnectionStrings");
            // 修改运行XML
            System.Xml.XmlDocument xDoc = new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            XmlNode xNode;
            XmlElement xElemKey;
            XmlElement xElemValue;

            xNode = xDoc.SelectSingleNode("//connectionStrings");

            xElemKey = (XmlElement)xNode.SelectSingleNode("//add[@name=\"" + DBUtility.ConKey + "\"]");
            if (xElemKey != null) xElemKey.SetAttribute("connectionString", newConString);
            else
            {
                xElemValue = xDoc.CreateElement("add");
                xElemValue.SetAttribute("name", DBUtility.ConKey);
                xElemValue.SetAttribute("connectionString", newConString);
                xElemValue.SetAttribute("providerName", "System.Data.SqlClient");
                xNode.AppendChild(xElemValue);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            MessageBox.Show(this,"您的数据源配置保存成功！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // 修改本身App.Config
            // ConfigurationManager.ConnectionStrings[DBUtility.ConKey].ConnectionString = newConString;
        }

        private void cbbAuthMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbbAuthMethod.SelectedIndex == 0)
            {
                this.txtUserName.Enabled = false;
                this.txtPassword.Enabled = false;
            }
            else
            {
                this.txtUserName.Enabled = true;
                this.txtPassword.Enabled = true;
            }
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(this.currentConStr))
                {
                    con.Open();
                    MessageBox.Show(this,"连接成功！","",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
            }
            catch (Exception)
            {
                MessageBox.Show(this, "对不起，连接失败！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(this.currentConStr))
                {
                    con.Open();
                    IFileBLL fileBll = BLLManager.CreateFileBLL();
                    Boolean result = fileBll.ClearData();
                    if (result)
                    {
                        MessageBox.Show(this, "数据清除成功！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(this, "数据清除失败，请联系管理员！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(this, "对不起，连接失败！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}
